package com.qianbei.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.qianbei.R;
import com.qianbei.bean.Carbean;
import com.qianbei.bean.LighterBean;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.bean.SearchBean;
import com.qianbei.bean.SelectOrderBean;
import com.qianbei.bean.SelectVehicleBean;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.view.NoScrollListView;
import com.qianbei.view.adapter.GetCarAdapter;
import com.qianbei.view.adapter.GetCarBean;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <pre>
 *     author : pwj
 *     e-mail : xxx@xx
 *     time   : 2019/03/14
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class LighterActivity extends BaseActivity {
    private static final String TAG = LighterActivity.class.getSimpleName();
//    @Bind(R.id.tv_brand)
//    TextView tvBrand;
//    @Bind(R.id.tv_model)
//    TextView tvModel;
//    @Bind(R.id.tv_color)
//    TextView tvColor;
//    @Bind(R.id.tv_km)
//    TextView tvKm;
    @Bind(R.id.listView)
    NoScrollListView listView;
    @Bind(R.id.et_big)
    EditText etBig;
    @Bind(R.id.et_small)
    EditText etSmall;
    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;
    private IUHFService iuhfService;
    private Gson gson = new Gson();
    private GetCarAdapter getCarAdapter;
    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);



    @Bind(R.id.cour_guoluType)
    TextView gulufeiLeixing;
    @Bind(R.id.cour_xiaofeiType)
    TextView xiaoFeiLeixing;
    @Bind(R.id.bing_youfei)
    EditText bingYoufei;
    @Bind(R.id.et_oil)
    EditText etOil;
    @Bind(R.id.bing_guolufei)
    EditText bingGuolufei;
    @Bind(R.id.bing_fadan)
    EditText bingFadan;
    @Bind(R.id.bing_chuche)
    EditText bingChuche;
    @Bind(R.id.bing_huiche)
    EditText bingHuiche;
    @Bind(R.id.bing_otherfei)
    EditText bingOtherfei;
    @Bind(R.id.bing_shuoming)
    EditText bingShuoming;

    final String[] oilType = {"油库", "油卡", "现金"};//1:油库 2：油卡 3：现金
    final String[] roadPayType = {"ETC", "现金"};//2: ETC 3: 现金

    public static final int MILAGE = 500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lighter);
        ButterKnife.bind(this);
        setTitle("驳运确认");
        mTitle.setrightTitle("扫描");
        initUHFService();
        getCarAdapter = new GetCarAdapter(this);
        listView.setAdapter(getCarAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getCarAdapter.setChecked(position);
            }
        });
    }

    @OnClick({R.id.cour_select1, R.id.cour_select2})
    public void onViewClicked(View view) {

        switch (view.getId()){
            case R.id.cour_select1:
                showDialog(oilType,"消费类型 - ",xiaoFeiLeixing);
                break;

            case R.id.cour_select2:
                showDialog(roadPayType,"过路费类型 - ",gulufeiLeixing);
                break;
        }
    }


    public void showDialog(final String select[], final String data, final TextView textView){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'女' 会被勾选上
         * 第三个参数给每一个单选项绑定一个监听器
         */
        builder.setSingleChoiceItems(select, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                type2 = which + 2;
                Toast.makeText(LighterActivity.this, "选定为：" + select[which], Toast.LENGTH_SHORT).show();
                textView.setText(data + select[which]);
                dialog.dismiss();
            }
        });

        builder.show();
    }

    private void initUHFService() {
        iuhfService = MyApplication.iuhfService;
        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {

                if (!ishow) {
                    handler.sendMessage(handler.obtainMessage(111, var1));
                }
            }
        });
        newWakeLock();
    }

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }

    boolean ishow = false;
    private Set<String> checked = new HashSet<String>();
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    selectVehiclebyRfid(var1.epc);
                    break;
                case 2:
                    iuhfService.newInventoryStop();
                    mTitle.setrightTitle("扫描");
                    isOpenDev.set(false);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 根据rfid查找车辆
     *
     * @param rfid
     */
    private void selectVehiclebyRfid(String rfid) {
        if (isOpenDev.get()) {
            iuhfService.newInventoryStop();
            mTitle.setrightTitle("扫描");
            isOpenDev.set(false);
        } else {
            handler.sendEmptyMessageDelayed(2, 2000);
        }
        SelectVehicleBean vehicleBean = new SelectVehicleBean();
        vehicleBean._number = 1;
        vehicleBean._page = 1;
        vehicleBean._pageSize = 10;
        vehicleBean._sortField = "_id";
        vehicleBean.rfid = rfid;
        RequeastBean1 bean1 = new RequeastBean1("selectByPage",
                "com.cygps.dubbo.commons.data.ICommonDataService",
                vehicleBean, "WT_VehicleEquipment");
        ServerControl sc = new ServerControl(bean1);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    try {
                        JSONArray js = sr.bodyData.optJSONArray("array");
                        List<Carbean> carbeans = gson.fromJson(js.toString(), new TypeToken<List<Carbean>>() {
                        }.getType());
                        if (carbeans != null && carbeans.size() != 0) {
                            Carbean carbean = carbeans.get(0);
                            selectOrderbyVehicle(carbean.vehicleNumber);
//                            updateCarStatus(carbean);
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        sc.OKpost1();
    }

//    private void updateCarStatus(Carbean carbean) {
//        tvBrand.setText(carbean.vehicleBrand);
//        tvModel.setText(carbean.vehicleModel);
//        tvColor.setText(carbean.vehicleColour);
//        tvKm.setText(carbean.totalKilometers);
//    }

    /**
     * 根据车牌号查询派车单
     *
     * @param name
     */
    private void selectOrderbyVehicle(String name) {
        SelectOrderBean orderBean = new SelectOrderBean();
        orderBean.vehicle = name;
        orderBean._sortField = "date";
        orderBean._page = 1;
        orderBean._pageSize = 10;
        orderBean._number = 1;
        orderBean.eventState = "1";
        orderBean.date = getNowDate();
        RequeastBean1 bean1 = new RequeastBean1("selectByPage",
                "com.cygps.dubbo.commons.data.ICommonDataService",
                orderBean, "WT_ScheduleManageCalendar");
        ServerControl sc = new ServerControl(bean1);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    JSONArray js = sr.bodyData.optJSONArray("array");
                    List<GetCarBean> carBeans = JSON.parseArray(js.toString(), GetCarBean.class);
                    getCarAdapter.setDatas(carBeans);
                    if (carBeans.size()>0) {
                        getCarAdapter.setChecked(carBeans.size() - 1);
                    }
                }
            }
        };
        new ProgressDialog(this).OKpost1(sc, "正在加载...");
    }

    @SuppressLint("SimpleDateFormat")
    private String getNowDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date());
    }

    @SuppressLint("StaticFieldLeak")
    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                mTitle.setrightTitle("正在扫描");

                //重复点扫描按钮时 只做一次上电操作
                if (isOpenDev.get() == false) {
                    isOpenDev.set(true);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            try {
                                if (iuhfService != null) {
                                    if (openDev()) {
                                        isOpenDev.set(false);
                                        return null;
                                    }
                                }
                                iuhfService.set_antenna_power(MyApplication.setValue);
                            } catch (Exception e) {
                                e.printStackTrace();
                                isOpenDev.set(false);
                                return null;
                            }

                            if (iuhfService == null) {
                                initUHFService();
                            }
                            iuhfService.newInventoryStart();
                            return null;
                        }
                    }.execute();

                }
                break;
            default:
                break;
        }
    }

    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        if (iuhfService.OpenDev() != 0) {
            new AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get()) {
                isOpenDev.set(false);
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
                //断电后选卡操作会失效，需要重新选卡（掩码）
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.tv_save)
    public void onViewClicked() {
        saveOrder();
    }

    private void saveOrder() {
        if (TextUtils.isEmpty(etBig.getText())) {
            new MsgAlert().show("请输入大箱数量");
            return;
        }
        if (TextUtils.isEmpty(etSmall.getText())) {
            new MsgAlert().show("请输入小箱数量");
            return;
        }
        int checkedPosition = getCarAdapter.getCheckedPosition();
        if (checkedPosition == -1) {
            new MsgAlert().show("请先勾选路线");
            return;
        }

        if (xiaoFeiLeixing.getText().toString().split(" - ").length < 2) {
            new MsgAlert().show("请选择消费类型");
            return;
        } else if (TextUtils.isEmpty(bingYoufei.getText().toString())) {
            new MsgAlert().show("请输入油费金额");
            return;
        } else if (TextUtils.isEmpty(etOil.getText().toString())) {
            new MsgAlert().show("请输入加油量");
            return;
        } else if (gulufeiLeixing.getText().toString().split(" - ").length < 2) {
            new MsgAlert().show("请选择过路费类型");
            return;
        } else if (TextUtils.isEmpty(bingGuolufei.getText().toString())) {
            new MsgAlert().show("请输入过路费金额");
            return;
        } else if (TextUtils.isEmpty(bingFadan.getText().toString())) {
            new MsgAlert().show("请输入罚单金额");
            return;
        } else if (TextUtils.isEmpty(bingChuche.getText().toString())) {
            new MsgAlert().show("请输入出车里程");
            return;
        } else if (TextUtils.isEmpty(bingHuiche.getText().toString())) {
            new MsgAlert().show("请输入回车里程");
            return;
        } else {
            try {
                float huicheVal = Float.parseFloat(bingHuiche.getText().toString());
                float chucheVal = Float.parseFloat(bingChuche.getText().toString());
                if (TextUtils.equals(bingChuche.getText(), bingHuiche.getText())) {
                    new MsgAlert().show("回车里程需大于出车里程");
                    return;
                }
                if (huicheVal < chucheVal) {
                    new MsgAlert().show("回车里程小于出车里程");
                    return;
                }
                if (huicheVal - chucheVal > MILAGE) {
                    new MsgAlert().show("回车里程过大比出车里程多500km");
                    return;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            String bigBoxCount = etBig.getText().toString();
            String smallBoxCount = etSmall.getText().toString();
            GetCarBean carBean = getCarAdapter.getItem(checkedPosition);
            LighterBean lighterBean = new LighterBean();
            lighterBean.box1 = bigBoxCount;
            lighterBean.box2 = smallBoxCount;
            lighterBean.jobId = carBean._id;
            lighterBean.cus_id = (carBean.customerAry == null || carBean.customerAry.size() == 0) ?
                    "" : carBean.customerAry.get(0).getId();
//            lighterBean.oilMoney = etOil.getText().toString().split(" - ")[1];
            lighterBean.oilMoney = bingYoufei.getText().toString();
            lighterBean.oilType = xiaoFeiLeixing.getText().toString().split(" - ")[1];
            lighterBean.roadToll = bingGuolufei.getText().toString();
            lighterBean.roadType = gulufeiLeixing.getText().toString().split(" - ")[1];
            lighterBean.ticket = bingFadan.getText().toString();
            lighterBean.outkm = bingChuche.getText().toString();
            lighterBean.returnKm = bingHuiche.getText().toString();
            lighterBean.otherPay = bingOtherfei.getText().toString();
            lighterBean.Descript = bingShuoming.getText().toString();
            lighterBean.oilNum = etOil.getText().toString();

            RequeastBean bean = new RequeastBean("saveWorkOrderBy",
                    "com.cygps.dubbo.WasteTransport.IInputKg",
                    lighterBean);
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("保存成功");
                        showTip();
                    }
                }
            };
            new ProgressDialog(this).OKpost(sc, "正在保存...");
        }
    }

    /**
     * 提示是否再新增驳运工单
     */
    private void showTip() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("是否添加新的驳运工单")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(AddLighterActivity.class);
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .show();
    }
}
